package com.jkl.webserver.Web.Controller;

import com.jkl.webserver.Tool.CopyFile;
import com.jkl.webserver.Tool.xFile;
import com.jkl.webserver.Web.Service.WebLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
public class WebLoginController {
    // 假设有一个服务层来处理实际的业务逻辑
    private final CopyFile copyFile;
    private final xFile xfile;
    private final WebLoginService LoginService;

    // 构造函数注入服务层
    @Autowired
    public WebLoginController(CopyFile copyFile, xFile xfile, WebLoginService LoginService) {
        this.copyFile = copyFile;
        this.xfile = xfile;
        this. LoginService =  LoginService;
    }

    //网页登录
    @GetMapping("/Login")
    public String loginPage(Model model, HttpServletRequest request){
        Cookie[] cookies =request.getCookies();
        if(cookies!=null)
        {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("email"))
                    model.addAttribute("email", cookie.getValue());
                if (cookie.getName().equals("password"))
                    model.addAttribute("password", cookie.getValue());
                if (cookie.getName().equals("remember"))
                    model.addAttribute("remember", cookie.getValue());
            }
        }
        model.addAttribute("Web",getLocalHostAddress(request));
        return "views/login/login";
    }

    //验证码获取
    @GetMapping("/verifyCode")
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response) {
        LoginService.generateCode(request,response);
    }

    //获取公共图片资源
    @GetMapping("/logoRes/{img}")
    public void getLogoRes(@PathVariable String img,HttpServletResponse response) throws IOException {
        String filePath = xfile.getBasePath() + "/publicBackground/" + img;
        response.setHeader("Cache-Control", "max-age=3600");
        response.setContentType("image/png");
        copyFile.byteCopy(filePath, response.getOutputStream());
    }

    @GetMapping("/loginRes/{img}")
    public void getLoginRes(@PathVariable String img,HttpServletResponse response) throws IOException {
        String filePath = xfile.getBasePath() + "/publicBackground/loginRes/" + img;
        response.setHeader("Cache-Control", "max-age=3600");
        response.setContentType("image/png");
        copyFile.byteCopy(filePath, response.getOutputStream());
    }

    @PostMapping("/Login")
    public String logging(Model model,@RequestParam String email,@RequestParam String password,@RequestParam String verifyCode,HttpServletRequest request,HttpServletResponse response){
        if(verifyCode.toLowerCase().equals(request.getSession().getAttribute("code")))//验证码正确
            switch (LoginService.WebVerify(request, email, password)) {
                case 0 : {
                    {//用户不存在
                        model.addAttribute("message1", "*用户不存在");
                    }
                }break;
                case 1 : {
                    {//密码错误
                        model.addAttribute("message2", "*密码错误");
                    }
                }break;
                case 2 : {//密码正确
                    String remember = request.getParameter("remember");
                    setCookies(response, email, password, remember);
                    return "redirect:/Index";
                }
            }
        else//验证码错误
            model.addAttribute("message3","*验证码错误");
        model.addAttribute("email", email);
        model.addAttribute("password", password);
        model.addAttribute("Web",getLocalHostAddress(request));
        return "views/login/login";
    }

    @GetMapping("/" )
    public String test(Model model){
        model.addAttribute("msg","hello");
        return "test";
    }

    private void setCookies(HttpServletResponse resp, String email, String password, String remember) {
        if (remember!=null) {
            Cookie cuser = new Cookie("email", email);
            Cookie cpwd = new Cookie("password", password);
            cuser.setMaxAge(60 * 60 * 24 * 7);
            cpwd.setMaxAge(60 * 60 * 24 * 7);

            Cookie rememberMe = new Cookie("remember", "true");
            rememberMe.setMaxAge(60 * 60 * 24 * 7);
            resp.addCookie(cuser);
            resp.addCookie(cpwd);
            resp.addCookie(rememberMe);
        } else {
            // 清除任何现有的记住密码Cookie
            Cookie cuser = new Cookie("email", email);
            Cookie cpwd = new Cookie("password", "");
            cuser.setMaxAge(60 * 60 * 24 * 7);
            cpwd.setMaxAge(0);
            Cookie rememberMe = new Cookie("remember", "");
            rememberMe.setMaxAge(0);
            resp.addCookie(cuser);
            resp.addCookie(cpwd);
            resp.addCookie(rememberMe);
        }
    }
    private String getLocalHostAddress(HttpServletRequest request){
        String scheme = request.getScheme(); // 例如: http
        String serverName = request.getServerName(); // 例如: localhost
        int serverPort = request.getServerPort(); // 例如: 8080
        return scheme+"://"+serverName+":"+serverPort;
    }
}
